package cn.sxt.userscenter.common.util;

import java.io.InputStream;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

@Component("regexUtil")
public class RegexUtil {
	@Resource
	private FileUtil fileUtil;
	// ${a}	
	//以()分组，双斜杠为转义字符，即${     a    }
	private String patt="(\\$\\{)(\\w+)(\\})";
	
	
	//编译前的内容aaa${aa}bb${bb}bb
	//编译前的内容aaaaabbbbbb
	public String replaceStr(String souStr,Map<String ,Object> paramsMap){
		//编译正则表达式
		Pattern pattern=Pattern.compile(patt);
		//获取匹配器
		Matcher matcher=pattern.matcher(souStr);
		
		StringBuffer sb=new StringBuffer();
		while(matcher.find()){
			
			//获取正则表达式的结果取第二组---
			String res=matcher.group(2);
			if(paramsMap.containsKey(res)){
				/* 如果map中包含键,就将键对应的值替换 */
				matcher.appendReplacement(sb, res+"");
			}
		}
		matcher.appendTail(sb);		
		return sb.toString();
	}
	
	
	//
	public String replaceFile(String fileName,Map<String ,Object> paramsMap){
		//从类加载其中读取文件
		InputStream is=ConstatFinalUtil.class.getClassLoader().getResourceAsStream(fileName);
		
		String fileContent=this.fileUtil.readFile(is);
		return this.replaceStr(fileContent, paramsMap);
	}
}
